package com.bawei.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.library_net.entity.ResponseEntity
import com.bawei.module_home.intent.SimpleTypeIntent
import com.bawei.module_home.model.entity.SimpleTypeEntity
import com.bawei.module_home.model.service.VideoTypeService
import com.bawei.module_home.state.SimpleTypeState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/25 09:21
 * @Description : SimpleTypeViewModel
 */
class SimpleTypeViewModel:BaseViewModel<SimpleTypeIntent>() {
    //网络请求
    val service:VideoTypeService by lazy{VideoTypeService()}
    //UIState
    private val _states = MutableStateFlow<SimpleTypeState>(SimpleTypeState.Init)//初始化默认的状态
    val state:StateFlow<SimpleTypeState>
        get() = _states

    //1:处理用户的意图
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    //2：判断意图类型-》发起网络请求
                    is SimpleTypeIntent.getSimpleType -> {
                        doSimpleType(it)
                    }
                }
            }
        }
    }
    //3：网络请求数据->更新state状态
    private fun doSimpleType(it: SimpleTypeIntent.getSimpleType) {
        viewModelScope.launch {
            flow{
                val simpleTypeVideo = service.aa()
                emit(simpleTypeVideo)
            }.catch { exception->
                    _states.value = SimpleTypeState.Error(exception)
            }.collect {
                val data = it.data
                //kotlin == === /java equals  ==
                if (data === null || data.equals("") || data.size === 0) {
                    _states.value = SimpleTypeState.Empty
                } else {
                    _states.value = SimpleTypeState.SimpleTypes(data)
                }


            }

        }

    }
}